package com.example.wzviewer.data;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.text.InputType;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.MainThread;
import androidx.core.util.Consumer;
import androidx.fragment.app.FragmentActivity;

/**
 * 统一处理“选择视频”：
 * 1) 选择本地视频（SAF） -> 返回 content:// Uri
 * 2) 选择网络视频（输入 http/https） -> 返回 Uri.parse(url)
 *
 * 使用：
 *   VideoChooser chooser = new VideoChooser(activity, uri -> {
 *       // 拿到用户选择的视频 Uri（本地或网络）
 *       videoView.play(uri);
 *   });
 *   btnSelect.setOnClickListener(v -> chooser.show());
 */
public class VideoChooser {

    private final FragmentActivity activity;
    private final Consumer<Uri> onPicked;

    private final ActivityResultLauncher<Intent> pickerLauncher;

    @MainThread
    public VideoChooser(FragmentActivity activity, Consumer<Uri> onPicked) {
        this.activity = activity;
        this.onPicked = onPicked;

        // 注册系统文件选择器（仅视频）
        this.pickerLauncher = activity.registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                        Uri uri = result.getData().getData();
                        if (uri != null) {
                            // 持久化读权限（下次进入仍可读）
                            final int flags = (result.getData().getFlags()
                                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
                            try {
                                activity.getContentResolver().takePersistableUriPermission(
                                        uri, flags | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            } catch (Exception ignored) {}
                            // 交给上层播放
                            onPicked.accept(uri);
                        }
                    }
                }
        );
    }

    /** 弹出主菜单：1. 选择本地视频  2. 选择网络视频 */
    @MainThread
    public void show() {
        new AlertDialog.Builder(activity)
                .setTitle("选择视频来源")
                .setItems(new CharSequence[]{"选择本地视频", "选择网络视频"}, (dlg, which) -> {
                    if (which == 0) {
                        showLocalSubMenu();
                    } else if (which == 1) {
                        showUrlInputDialog();
                    }
                })
                .show();
    }

    /** 二级菜单（按你的需求先放“选择本地视频1”占位） */
    @MainThread
    private void showLocalSubMenu() {
        new AlertDialog.Builder(activity)
                .setTitle("本地视频")
                .setItems(new CharSequence[]{"选择本地视频1"}, (d, w) -> openLocalPicker())
                .show();
    }

    /** 打开 SAF 选择本地视频 */
    @MainThread
    private void openLocalPicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("video/*");
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        pickerLauncher.launch(intent);
    }

    /** 输入网络 URL -> 回调 Uri */
    @MainThread
    private void showUrlInputDialog() {
        EditText et = new EditText(activity);
        et.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
        et.setHint("输入视频 URL（https://...）");
        et.setText("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"); // 示例可删

        new AlertDialog.Builder(activity)
                .setTitle("播放网络视频")
                .setView(et)
                .setPositiveButton("播放", (dialog, which) -> {
                    String s = et.getText() == null ? "" : et.getText().toString().trim();
                    if (!isValidUrl(s)) {
                        Toast.makeText(activity, "请输入有效的 http/https 地址", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    onPicked.accept(Uri.parse(s));
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private static boolean isValidUrl(String s) {
        if (s == null || s.isEmpty()) return false;
        try {
            Uri u = Uri.parse(s);
            String scheme = u.getScheme();
            return "http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme);
        } catch (Exception e) {
            return false;
        }
    }
}